//
//  CLWebBottomBar.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2016/11/6.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLWebBottomBar.h"
#import "CLWebViewManager.h"
#import "CLDelegateManager+WebViewDelegate.h"
#import "CLWebContainerView.h"

@interface CLWebBottomBar () <WebViewDelegate, CLWebViewDelegate>

@property (nonatomic, weak) UIBarButtonItem *refreshOrStopItem;
@property (nonatomic, weak) UIBarButtonItem *backItem;
@property (nonatomic, weak) UIBarButtonItem *forwardItem;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, weak) CLWebContainerView *containerView;

@end

@implementation CLWebBottomBar

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initializeView];
        [[CLDelegateManager sharedInstance] registerDelegate:self forKey:kDelegateManagerWebView];
        [[CLDelegateManager sharedInstance] addWebViewDelegate:self];
        [Notifier addObserver:self selector:@selector(handletabSwitch:) name:kWebTabSwitch object:nil];
        [Notifier addObserver:self selector:@selector(updateForwardBackItem) name:kWebHistoryItemChangedNotification object:nil];
    }
    
    return self;
}

- (void)initializeView{
    
    UIBarButtonItem *backItem = [self createBottomToolBarButtonWithImage:TOOLBAR_BUTTON_BACK_HILIGHT_STRING tag:CLBottomToolBarTagBack];
    self.backItem = backItem;
    [self.backItem setEnabled:NO];
    
    UIBarButtonItem *forwardItem = [self createBottomToolBarButtonWithImage:TOOLBAR_BUTTON_FORWARD_HILIGHT_STRING tag:CLBottomToolBarTagForward];
    self.forwardItem = forwardItem;
    [self.forwardItem setEnabled:NO];
    
//    UIBarButtonItem *refreshOrStopItem = [self createBottomToolBarButtonWithImage:TOOLBAR_BUTTON_STOP_STRING tag:CLBottomToolBarTagRefreshOrStop];
//    self.isRefresh = NO;
//    self.refreshOrStopItem = refreshOrStopItem;
    
    UIBarButtonItem *novelItem = [self createBottomToolBarButtonWithImage:@"cl_bottombar_novel" tag:CLBottomToolBarTagNovel];
    
    
    UIBarButtonItem *multiWindowItem = [self createBottomToolBarButtonWithImage:TOOLBAR_BUTTON_MULTIWINDOW_STRING tag:CLBottomToolBarTagMultiWindow];
    
    UIBarButtonItem *settingItem = [self createBottomToolBarButtonWithImage:TOOLBAR_BUTTON_MORE_STRING tag:CLBottomToolBarTagMore];

    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    [self setItems:@[flexibleItem,novelItem,flexibleItem,multiWindowItem,flexibleItem,backItem,flexibleItem,forwardItem,flexibleItem,settingItem,flexibleItem] animated:NO];
}

- (UIBarButtonItem *)createBottomToolBarButtonWithImage:(NSString *)imageName tag:(NSInteger)tag{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(handleBottomToolBarButtonClicked:)];
    item.tag = tag;
    item.width = self.width / 5.0f;
    
    return item;
}

- (void)handleBottomToolBarButtonClicked:(UIBarButtonItem *)item{
    CLBottomToolBarTag tag;
    
    if (item.tag == CLBottomToolBarTagRefreshOrStop) {
        tag = self.isRefresh ? CLBottomToolBarTagRefresh : CLBottomToolBarTagStop;
        [self setToolBarButtonRefreshOrStop:!_isRefresh];
    }
    else {
        tag = item.tag;
    }
    
    if ([self.browserButtonDelegate respondsToSelector:@selector(browserBottomToolBarButtonClickedWithTag:)]) {
        [self.browserButtonDelegate browserBottomToolBarButtonClickedWithTag:tag];
    }
}

- (void)setToolBarButtonRefreshOrStop:(BOOL)isRefresh{
    NSString *imageName = isRefresh ? TOOLBAR_BUTTON_REFRESH_STRING : TOOLBAR_BUTTON_STOP_STRING;
    self.isRefresh = isRefresh;
    
    self.refreshOrStopItem.image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    if (isRefresh) {
//        [self.delegate ]
    }
}

- (void)updateForwardBackItem{
    if (self.containerView.webView) {
        BOOL backItemEnabled = [self.containerView.webView canGoBack];
        BOOL forwardItemEnabled = [self.containerView.webView canGoForward];
        [self.backItem setEnabled:backItemEnabled];
        [self.forwardItem setEnabled:forwardItemEnabled];
        
        [self.backItem setImage:[[UIImage imageNamed:(backItemEnabled ?TOOLBAR_BUTTON_BACK_STRING : TOOLBAR_BUTTON_BACK_HILIGHT_STRING)] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [self.forwardItem setImage:[[UIImage imageNamed:(forwardItemEnabled ? TOOLBAR_BUTTON_FORWARD_STRING : TOOLBAR_BUTTON_FORWARD_HILIGHT_STRING)] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
}

#pragma mark - CLWebViewDelegate

- (void)webViewDidFinishLoad:(CLWebView *)webView {
    if (IsCurrentWebView(webView)) {
        [self updateForwardBackItem];
        [self setToolBarButtonRefreshOrStop:YES];
    }
}

- (void)webView:(CLWebView *)webView didFailLoadWithError:(NSError *)error {
    if (IsCurrentWebView(webView)) {
        [self updateForwardBackItem];
        [self setToolBarButtonRefreshOrStop:YES];
    }
}

- (void)webViewForMainFrameDidFinishLoad:(CLWebView *)webView {
    if (IsCurrentWebView(webView)) {
        [self setToolBarButtonRefreshOrStop:YES];
    }
}

- (void)webViewForMainFrameDidCommitLoad:(CLWebView *)webView {
    if (IsCurrentWebView(webView)) {
        [self setToolBarButtonRefreshOrStop:NO];
    }
}

- (BOOL)webView:(CLWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (IsCurrentWebView(webView)) {
        [self updateForwardBackItem];
        [self setToolBarButtonRefreshOrStop:NO];
    }
    
    return YES;
}
- (BOOL)webView:(CLWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (IsCurrentWebView(webView)) {
        [self updateForwardBackItem];
        [self setToolBarButtonRefreshOrStop:NO];
    }
    
    return YES;
}

- (void)webViewForMainFrameDidChangeHtml:(CLWebView *)webView {
    
}

- (void)webView:(CLWebView *)webView hiddenBottomBar:(BOOL)isHiddenBottomBar {
    if (IsCurrentWebView(webView)) {
        self.hidden = isHiddenBottomBar;
    }
}

#pragma mark - kWebTabSwitch notification handler

- (void)handletabSwitch:(NSNotification *)notification{
    CLWebView *webView = [notification.userInfo objectForKey:@"webView"];
    if ([webView isKindOfClass:[CLWebView class]]) {
        [self updateForwardBackItem];
        [self setToolBarButtonRefreshOrStop:webView.isMainFrameLoaded];
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"webView"] && [object isKindOfClass:[CLWebContainerView class]]) {
        self.containerView = object;
    }
}

#pragma mark - Dealloc

- (void)dealloc{
    [Notifier removeObserver:self name:kWebTabSwitch object:nil];
    [Notifier removeObserver:self name:kWebHistoryItemChangedNotification object:nil];
    [[[CLWebViewManager sharedInstance] clContainerView] removeObserver:self forKeyPath:@"webView" context:nil];
}

@end
